/**
 * File BaseDAO.java created by Pablo Díaz Fernández
 * on Dec 21, 2011 for the project supply-chain-simulator
 */
package org.lsk.pfc.scsim.model.persistence.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Example;
import org.lsk.pfc.scsim.model.persistence.dto.BaseDTO;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * @author Pablo Díaz Fernández
 * 
 */
public abstract class BaseDAO extends HibernateDaoSupport {

	/**
	 * Retrieves the object specified by the id from the database.
	 * 
	 * @param dto
	 *            DTO that contains the identifier of the object to retrieve.
	 * @return {@link BaseDTO} found or <code>null</code> if no one matches.
	 */
	protected final BaseDTO retrieve(final BaseDTO dto) {
		return getHibernateTemplate()
		        .get(dto.getClass(), dto.getId());
	}

	/**
	 * Finds all object that match with the specified template.
	 * 
	 * @param dto
	 *            {@link BaseDTO} template to search.
	 * @return {@link List} of {@link BaseDTO} found.
	 */
	@SuppressWarnings("unchecked")
    protected final List<? extends BaseDTO> list(final BaseDTO dto) {
		Criteria criteria = getSession().createCriteria(dto.getClass());
		criteria.add(Example.create(dto));
		return criteria.list();
	}

	/**
	 * Creates the {@link BaseDTO} in database or updates it if already exists.
	 * 
	 * @param dto
	 *            Object to persist.
	 * @return Object persisted.
	 */
	protected final BaseDTO createOrUpdate(final BaseDTO dto) {
		getHibernateTemplate().saveOrUpdate(dto);
		return dto;
	}

	/**
	 * Deletes the object from the database.
	 * 
	 * @param dto
	 *            DTO that contains the identifier of the object to delete.
	 */
	protected final void delete(final BaseDTO dto) {
		Object aux = getHibernateTemplate().load(dto.getClass(), dto.getId());
		getHibernateTemplate().delete(aux);
	}

}
